﻿#region Usings

using System;
using System.Threading;
using InfoService.Feeds;
using InfoService.Twitter;
using InfoService.Weather;

#endregion

namespace InfoService.Utils
{
    public static class UpdateTimer
    {
        #region Delegates

        public delegate void UpdatePropertiesHandler();

        #endregion

        private static readonly Logger logger = Logger.GetInstance();

        private static bool _updateInProgress;
        private static TimerCallback _timerDelegate;
        private static Timer _timer;
        private static readonly UpdatePropertiesHandler[] UpdateDelegate = new UpdatePropertiesHandler[3];
        private static event UpdatePropertiesHandler UpdateProperties;
        public static event UpdatePropertiesHandler OnTimeForUpdateProperties
        {
            add
            {
                if (value.Method.DeclaringType.Name == "FeedUpdater")
                {
                    logger.WriteLog("FeedUpdater registered for update timer", LogLevel.Debug, InfoServiceModul.InfoService);
                    UpdateDelegate[1] = value;
                }
                if (value.Method.DeclaringType.Name == "TwitterUpdater")
                {
                    logger.WriteLog("TwitterUpdater registered for update timer", LogLevel.Debug, InfoServiceModul.InfoService);
                    UpdateDelegate[2] = value;
                }
                if (value.Method.DeclaringType.Name == "WeatherUpdater")
                {
                    logger.WriteLog("WeatherUpdater registered for update timer", LogLevel.Debug, InfoServiceModul.InfoService);
                    UpdateDelegate[0] = value;
                }
            }
            remove { UpdateProperties -= value; }
        }


        /*
        private GUIDialogNotify _dialogUpdateNotify;
*/
        private static void InfoTimerCallback(Object stateInfo)
        {

            if (_updateInProgress) return;
            if (UpdateProperties == null) return;
            _updateInProgress = true;
            UpdateProperties();
            _updateInProgress = false;
        }
        public static void SetTimer()
        {
            //Set timer only if min. 1 Service is enabled
            if (FeedService.Enabled || TwitterService.Enabled || WeatherService.Enabled)
            {
                UpdateProperties = (UpdatePropertiesHandler)Delegate.Combine(UpdateDelegate);
                logger.WriteLog("Set Timer callback to 60 seconds", LogLevel.Debug, InfoServiceModul.InfoService);
                _timerDelegate = InfoTimerCallback;
                _timer = new Timer(_timerDelegate, null, 0, 60000);
            }
        }
    }
}
